<template>
   <div class="searchHeader">
        <van-search class="search" @search="toSearchGoodsList" v-model="keyword" @click-input="click" :placeholder="keyword" @update:model-value="dealAfterHandler" />
        <span @click="toHome">取消</span>
   </div>
   <router-view @getDefaultKeyword="getDefaultKeyword" :realTimeKeywordList="realTimeKeywordList" @getRealKeyword="getRealKeyword" @refreshHistoryKey="refreshHistoryKey"></router-view>
</template>

<script setup lang='ts'>
import { onMounted, onUnmounted, ref, watch } from 'vue';
import { useRouter } from 'vue-router';
import * as _ from 'lodash'
import searchApi from '@/api/search'
import { showNotify } from 'vant';

const keyword = ref('')
const router = useRouter()
const click = () => {
    console.log('test');
    router.push('/search')
}

// 点击取消跳转到主页
const toHome = ()=>{
    router.push('/')
}
// 用于存储搜索记录
const kwdList = ref<string[]>([])
// console.log(kwdList);
// 当页面重新挂载的时候也需要重新读取历史记录
const refreshHistoryKey = ()=>{
    kwdList.value = JSON.parse(localStorage.getItem('KwdList') as string) || []
}
const toSearchGoodsList = ()=>{
    // 当确定了搜索之后将搜索的关键字存储到 localStorage 中
    kwdList.value.push(keyword.value)
    localStorage.setItem('KwdList',JSON.stringify(kwdList.value))
    router.push(`/search/searchGoodsList?keyword=${keyword.value}`)
}

// 获取到默认搜索的函数
const getDefaultKeyword = (str:string)=>{
    keyword.value = str
}


// 用于存储实时获取到的搜索数据
const realTimeKeywordList = ref([])
// 实时搜索
const getRealTimeData = async ()=>{
    try {
        let result = await searchApi.getRealTimeKeywordList(keyword.value)
        console.log('获取到的实时搜索数据',result);
        
        realTimeKeywordList.value = result.data
    } catch (error) {
        showNotify({ type: 'danger', message: '获取数据失败，请重试' });
    }
}
// 当输入是触发的函数
const inputHandler = ()=>{
    // console.log('触发了');
    localStorage.setItem('keywordPrefix',keyword.value)
    getRealTimeData()
}
// 定义防抖的函数
const dealAfterHandler = _.debounce(inputHandler,300,{
    leading:true,
    trailing:true
})

// 当点击实时搜索弹框中的某条数据时，触发此自定义事件的回调
const getRealKeyword = (key:string)=>{
    keyword.value = key
    toSearchGoodsList()
}


onMounted(()=>{
    refreshHistoryKey()
})

onUnmounted(() => {
    localStorage.removeItem('keywordPrefix')
})
</script>

<style scoped>
.searchHeader {
    display: flex;
    border-bottom: .03rem solid #eee;
}
.searchHeader span {
    font-size: .43rem;
    line-height: 1.5rem;
    margin-left: .13rem;
}
.searchHeader .search{
    width: 8.5rem;
}
</style>